import datetime
from flask import Blueprint,request,jsonify
from flask.json import JSONEncoder
import requests

from views.db import Db

import json

from utils.jwtc import myjwt

from utils.Make_password import make_password

from utils.myfile import MyFile

from utils.redis import rs

from utils.acl import ACL

import redis

import re

from views.db import db

from utils.acl import  acl

from utils.myfile import get_data

import time

import functools

bp_user = Blueprint("user",__name__)



@bp_user.route('/loginM',methods = ['POST','GET'])
def loginM():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        print(data)
        sql = """select * from user where username = '%s'"""%(data['username'])
        res = db.get_one(sql)
        print(sql)
        print(res)
        if res:
            if res['password'] == data['password']:
                uid = res['id']
                token = myjwt.encode_jwt({'data':{'uid':res['id']}})
                ress = acl.get_vue(uid)
                # 把url存入redis,
                rs.insert_set('users'+str(uid),ress)
                aa = rs.find_set('users'+str(uid))
                print(aa)
                return jsonify({'code':200,"mes":"登陆成功","token":token,'uid':uid,"url":aa})
            else:
                return jsonify({'code': 20021, "mes": "密码错误"})
        else:
            return jsonify({'code': 20021,"mes":"账户不存在"})

#构建2层分类
def getresdata(data):
    # 把顶级拿出来放到列表中
    list = []
    idlist=[]
    for i in data:
        id = i['pid']
        if id not in idlist:
            list.append({'id':id,'name':i['pname'],'son':[]})
            idlist.append(id)
    # 变理顶级列表，在遍历数据，把子类加到顶级列表
    for j,value in enumerate(list):

        for i in data:
        
            if value['id'] == i['pid']:
                
                list[j]['son'].append({'id':i['id'],'name':i['name'],'url':i['url']})
    return list



@bp_user.route('/getResource')

def getResource():

    uid = 1

    res = acl.get_resourcelist(uid,1) 

    mes = getresdata(res)

    return jsonify({'list':mes})


# 角色列表
@bp_user.route('/rolelist')
def rolelist():

    sql = " select * from role "

    res = db.get_all(sql)

    return jsonify({"code":200,"list":res})

# 资源列表
@bp_user.route('/resourcelist')
def resourcelist():

    id = request.args.get('id')

    if id:

        sql = "select resourceid from role_resource where roleid = %d" % (id)

        res = db.get_all(sql)

        list = []

        for i in res:

            list.append(i['resourceid'])
    
    else:
        time.sleep(1)
        sql = " select * from resource "
        list = db.get_all(sql)

    return jsonify({"code":200,"list":list})


# 配置资源接口
@bp_user.route('/setrole',methods=['GET','POST'])
def setsole():
    if request.method == 'POST':
        data = get_data()
        # 先删除已有的资源
        id = request.args.get('id')
        sql = 'delete from role_resource where roleid= %d' % (int(id))
        db.update(sql)
        # 配置新的资源
        ids = []
        for i in data():
            ids.append(i)
        for i in ids:
            sql1 = 'insert into role_resource(role_id,resource_id) values({},{})'.format(int(id),i)
            db.update(sql1)
        return jsonify({'code':200,'msg':'配置成功'})

@bp_user.route('/ggg')
def ggg():
    uid = 2
    res = acl.get_interface_reslist(uid)
    return jsonify({'list':res})
 

@bp_user.route('/getresource_pid',methods=['GET','POST'])
def getresource_pid():

    if request.method == 'POST':
        id = request.args.get('pid')
        time.sleep(1)
        sql = "select r.id,r.name as roname from resource as r left join role_resource as rr on r.id=rr.resourceid where rr.roleid=%d" % (int(id))
        res = db.get_all(sql)
        return jsonify({'code': 200, 'list': res})
    else:
        time.sleep(1)
        pid = request.args.get('pid')
        sql1 = "select * from role where pid=%d" % (int(pid))
        res1 = db.get_all(sql1)
        return jsonify({'code': 200, 'list': res1})


@bp_user.route('/getusers')
def getusers():
    sql = "select id,username,phone from user"
    res = db.get_all(sql)
    return jsonify({'code':200,'list':res})


@bp_user.route('/user_role')
def user_role():

    uid = request.args.get('userid')
    roleid = request.args.get('rid')
    sql = "select * from user_role where uid= %d" % (int(uid))
    res = db.get_one(sql)
    if res:
        sql1 = "select role_id2 from mutex where role_id1=%d" % (int(res['role_id']))
        res1 = db.get_all(sql1)
        print(res1)
        list = []
        for i in res1:
            list.append(i['role_id2'])
        if int(roleid) in list:
            return jsonify({'code':10020,"msg":'角色互斥'})
        sql2 = "insert into user_role(role_id2) values(%d) where uid=%d"% (int(roleid),int(uid))
        db.update(sql2)
        return jsonify({'code':200,"msg":'添加成功'})
    else:
        sql2 = "insert into user_role(user_id,role_id1) values({})".format(int(uid), int(roleid))
        db.update(sql2)
        return jsonify({'code': 200, "msg": '添加成功'})


# 用装饰器实现level为003在2021-10-01，2022-10-10时间段内内网对某个资源只有读取的权限
import datetime
def timer(func):
    @functools.wraps(func)
    def decor(*args, **kwargs):
        token=request.headers['Token']

        num=myjwt.decode_jwt(token)
        data = rs.get_all_hash('abac')
        ip=request.remote_addr
        times = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d")
        for (key, value) in data.items():
            if key == 'ip':
                if str(value)!=str(ip):
                    return 'ip限制'
            if key=='time':
                starttime=eval(value)[0]
                end=eval(value)[1]
                if starttime>times and times>end:
                    return '时间限制'
            if key=='role':
                sql = "select role_id from users where id=%s" % num['data']['uid']
                roleid=db.get_one(sql)
                if roleid['role_id'] !=int(value):
                    return '角色限制'
            if request.method != 'GET':
                return '请求方法限制'
        return  func( *args, **kwargs)
    return decor



@bp_user.route('/roleM',methods=['GET','POST','PUT','DELETE'])

def roleM():

    return 'hhhh'


import time
@bp_user.route('/hash_shu',methods=['GET','POST'])
@timer
def hash_shu():
    rs.insert_hash('abac','ip','127.0.0.1')
    rs.insert_hash('abac','time',"['2020-10-15','2022-1-30']")
    rs.insert_hash('abac','role','1')
    data=rs.get_all_hash('abac')

    times=datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d")
    for (key,value) in data.items():
        if key=='time':
            print(eval(value)[0])
    return 'ok'




  

        
                   
                   
                    
            
